
<template>
  <div style="width:800px">
    <div id="my-navigation" class="navigation">
      <div class="item" v-for="item in 6" :key="item" :data-id="item">
        {{ item }}
      </div>
    </div>
    <h1>只有行可以拖拽</h1>
    <el-table :data="tableData" border row-key="id" align="left">
      <el-table-column prop="date" label="推拽">
        <template slot-scope="scope">
          <div class="draggable">draggable</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="日期">
      </el-table-column>
      <el-table-column prop="name" label="姓名">
      </el-table-column>
      <el-table-column prop="address" label="地址">
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import Sortable from 'sortablejs';//引入插件
export default {
  data() {
    return {
      tableData: [//表格数据
        {
          id: '1',
          date: '2016-05-02',
          name: '王小虎1',
          address: '上海市普陀区金沙江路 100 弄'
        },
        {
          id: '2',
          date: '2016-05-04',
          name: '王小虎2',
          address: '上海市普陀区金沙江路 200 弄'
        },
        {
          id: '3',
          date: '2016-05-01',
          name: '王小虎3',
          address: '上海市普陀区金沙江路 300 弄'
        },
        {
          id: '4',
          date: '2016-05-03',
          name: '王小虎4',
          address: '上海市普陀区金沙江路 400 弄'
        }
      ]
    }
  },
  mounted() {
    var el = document.getElementById('my-navigation');
    //设置配置
    var ops = {
      animation: 200,
      group: '',
      draggable: '.item', // 要拖动的目标
      disabled: false, //是否禁用拖拽和排序
      dataIdAttr: 'data-id', //指定获取拖动后排序的属性
      //拖动结束
      onEnd: function (evt) {
        console.log(evt);
        //获取拖动后的排序
        var arr = sortable.toArray();
        // arr数组里的值是 data-id 的顺序
        console.log({ evt, arr });
      },
    };
    //初始化
    var sortable = Sortable.create(el, ops);
    // 阻止默认行为
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
    };
    this.rowDrop()//行拖拽
  },
  methods: {
    //行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        animation: 200,
        draggable: '.el-table__row', // 要拖动的目标
        onEnd(evt) {
          console.log(evt);
          let { newIndex, oldIndex } = evt;
          if (newIndex == oldIndex) return
          _this.tableData.splice(
            newIndex,
            0,
            _this.tableData.splice(oldIndex, 1)[0]
          )
          var newArray = _this.tableData.slice(0)
          _this.tableData = []
          _this.$nextTick(function () {
            _this.tableData = newArray
          })
        }
      })
    },

  }
}
</script>